package com.wzh.musichome.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzh.musichome.common.ConstantCode;
import com.wzh.musichome.common.ResponseTemplate;
import com.wzh.musichome.entity.pojo.Singer;
import com.wzh.musichome.entity.pojo.Spectrum;
import com.wzh.musichome.entity.dto.SongDTO;
import com.wzh.musichome.entity.pojo.Song;
import com.wzh.musichome.service.SongService;
import com.wzh.musichome.service.SpectrumService;
import com.wzh.musichome.utils.FastdfsClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 歌曲 前端控制器
 * </p>
 *
 * @author wzh
 * @since 2020-12-10
 */
@RestController
@RequestMapping("/song")
public class SongController {

    @Autowired
    private SongService songService;
    @Autowired
    private SpectrumService spectrumService;

    @Autowired
    private FastdfsClientUtil fastdfsClientUtil;

    /**
     * 添加歌曲
     */
    @PostMapping("/add")
    public Object addSong(HttpServletRequest request, @RequestParam("file") MultipartFile mpFile) {
        JSONObject jsonObject = new JSONObject();
        //获取前端传来的参数
        String singerId = request.getParameter("singerId").trim();  //所属歌手id
        String name = request.getParameter("name").trim();          //歌名
        String introduction = request.getParameter("introduction").trim();          //简介
        String pic = ConstantCode.defaultImgUrl;                     //默认图片
        String lyric = request.getParameter("lyric").trim();     //歌词
        //上传歌曲文件
        if (mpFile.isEmpty()) {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "歌曲上传失败");
            return jsonObject;
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = mpFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        //存储到数据库里的相对文件地址
        String storeUrlPath = "/song/" + fileName;
        try {
            mpFile.transferTo(dest);

            Song song = new Song();
            song.setSingerId(Integer.parseInt(singerId));
            song.setName(name);
            song.setIntroduction(introduction);
            song.setPic(pic);
            song.setLyric(lyric);
            song.setUrl(storeUrlPath);
            boolean flag = songService.save(song);
            if (flag) {
                jsonObject.put("code", 1);
                jsonObject.put("msg", "保存成功");
                jsonObject.put("avator", storeUrlPath);
                return jsonObject;
            }
            jsonObject.put("code", 0);
            jsonObject.put("msg", "保存失败");
            return jsonObject;
        } catch (IOException e) {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "保存失败" + e.getMessage());
        } finally {
            return jsonObject;
        }
    }


    /**
     * 根据歌手id查询歌曲
     */
    @GetMapping("/singer/detail/{id}")
    public Object songOfSingerId(Page<Song> page, @PathVariable int id) {
        QueryWrapper<Song> wrapper = new QueryWrapper<>();
        wrapper.eq("singer_id", id);
        try {
            Page<Song> list = songService.page(page, wrapper);
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            if (list.getTotal() > 0) {
                data.setMsg("查询成功,共" + list.getTotal() + "条");
            } else {
                data.setMsg("该歌手在本站没有歌曲");
            }
            data.setData(list);
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "拆查询失败！！ 具体原因" + e.getMessage());
        }
    }

    /**
     * 修改歌曲
     */
    @PostMapping("/update")
    public Object updateSong(@RequestBody SongDTO songDTO) {
        Song song = songService.getById(songDTO.getId());
        BeanUtils.copyProperties(songDTO, song);
        try {
            boolean b = songService.saveOrUpdate(song);
            if (b) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("更新成功");
                return data;
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPDATE, "更新失败！！ 具体原因" + e.getMessage());
        }
        return 0;
    }

    @PostMapping("/delete/{id}")
    public Object deleteSong(@PathVariable Integer id) {
        try {
            Song byId = songService.getById(id);
            String[] split = byId.getName().split(" - ");
            String fileName = split[1] + ".mp3";
            //文件路径
            String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song" + System.getProperty("file.separator") + fileName;
            boolean b = songService.removeById(id);
            QueryWrapper<Spectrum> wrapper = new QueryWrapper<>();
            wrapper.eq("song_id", id);
            boolean remove = spectrumService.remove(wrapper);
            boolean fileDel = false;
            File file = new File(filePath);
            if (file.exists()) {
                System.gc();
                fileDel = file.delete();
                System.out.println("是否删除成功" + fileDel);
            }

            if (b && remove && fileDel) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("删除成功");
                return data;
            } else {
                return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_DELETE, "删除失败！！ ");
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_DELETE, "删除失败！！ 具体原因" + e.getMessage());

        }

    }


    /**
     * 更新歌曲图片
     */
    @PostMapping("/updateSongPic")
    public Object updateSingerPic(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id") int id) {
        try {
            Song byId = songService.getById(id);
            if (!byId.getPic().equals(ConstantCode.defaultImgUrl)) {
                String[] split = byId.getPic().split("\\.");
                String sltUrl = split[0] + "_60x60." + split[1];
                fastdfsClientUtil.deleteFile(byId.getPic());
                fastdfsClientUtil.deleteFile(sltUrl);
            }
            String url = fastdfsClientUtil.upload(avatorFile);
            Song song = new Song();
            song.setId(id);
            song.setPic(url);
            boolean flag = songService.saveOrUpdate(song);
            if (flag) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("图片更改成功");
                return data;
            }
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败");
        } catch (IOException e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败" + e.getMessage());
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败" + e.getMessage());
        }
    }

    /**
     * 上传曲谱(上传的同时需要把之前的谱先删除)
     */
    @PostMapping("/uploadSpectrum")
    public Object uploadSpectrum(MultipartFile[] files, @RequestParam("id") int id) {
        int i = 0;
        try {
            QueryWrapper<Spectrum> wrapper = new QueryWrapper<>();
            wrapper.eq("song_id", id);
            List<Spectrum> list1 = spectrumService.list(wrapper);
            if (list1.size() != 0) {
                try {
                    for (Spectrum spectrum : list1) {
                        String spectrumUrl = spectrum.getSpectrumUrl();
                        String[] split = spectrumUrl.split("\\.");
                        String sltUrl = split[0] + "_60x60." + split[1];
                        fastdfsClientUtil.deleteFile(spectrumUrl);
                        fastdfsClientUtil.deleteFile(sltUrl);
                    }
                } catch (Exception e) {
                    return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_DELETE, "文件服务器图片删除失败" + e.getMessage());
                }
            }
            spectrumService.remove(wrapper);
            for (MultipartFile item : files) {
                String url = fastdfsClientUtil.upload(item);
                Spectrum spectrum = new Spectrum();
                spectrum.setSongId(id);
                spectrum.setSpectrumUrl(url);
                boolean flag = spectrumService.save(spectrum);
                if (flag) i++;
            }
            if (i == files.length) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("曲谱上传成功");
                return data;
            } else {
                return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "曲谱上传失败");
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "曲谱上传失败" + e.getMessage());
        }
    }


    @GetMapping("/getSpectrum")
    public Object getSpectrum(@RequestParam("songId") int songId) {
        QueryWrapper<Spectrum> wrapper = new QueryWrapper<>();
        wrapper.eq("song_id", songId);
        try {
            List<Spectrum> list = spectrumService.list(wrapper);
            if (list.size() == 0) {
                return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY_EMPTY, "请点击右下角联系管理员 先上传谱");
            }
            List<String> urls = list.stream().map(e -> "http://192.168.73.129:8001/" + e.getSpectrumUrl()).collect(Collectors.toList());
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("曲谱查找成功");
            data.setData(urls);
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "曲谱查找失败" + e.getMessage());
        }
    }


    /**
     * 更新歌曲
     */
    @PostMapping("/updateSongUrl")
    public Object updateSongUrl(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id") int id) {
        if (avatorFile.isEmpty()) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片上传失败");
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = avatorFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/song/" + fileName;
        try {
            avatorFile.transferTo(dest);
            Song song = new Song();
            song.setId(id);
            song.setPic(storeAvatorPath);
            boolean flag = songService.saveOrUpdate(song);
            if (flag) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("上传成功");
                return data;
            }
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "歌曲上传失败");
        } catch (IOException e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "歌曲上传失败" + e.getMessage());
        }
    }


    @GetMapping("/singer/detail")
    public Object songOfSingerId(@RequestParam Integer singerId) {
        try {
            QueryWrapper<Song> wrapper = new QueryWrapper<>();
            wrapper.eq("singer_Id", singerId);
            List<Song> list = songService.list(wrapper);
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("查询成功");
            data.setData(list);
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查找失败" + e.getMessage());
        }
    }

    /**
     * 根据歌曲id查询歌曲对象
     */
    @GetMapping("/detail")
    public Object detail(@RequestParam int songId) {
        try {
            Song song = songService.getById(songId);
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("查询成功");
            data.setData(song);
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查找失败" + e.getMessage());
        }
    }

    /**
     * 根据歌曲名字精确查询歌曲
     */
    @GetMapping("/songOfSongName")
    public Object songOfSongName(@RequestParam String songName) {
        QueryWrapper<Song> wrapper = new QueryWrapper<>();
        wrapper.eq("name", songName);
        try {
            List<Song> list = songService.list(wrapper);
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("查询成功");
            data.setData(list);
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查找失败" + e.getMessage());

        }
    }

    /**
     * 根据歌曲名字模糊查询歌曲
     */
    @GetMapping("/likeSongOfName")
    public Object likeSongOfName(Page<Song> page, @RequestParam String songName) {
        QueryWrapper<Song> wrapper = new QueryWrapper<>();
        wrapper.like("name", songName);
        try {
            Page<Song> list = songService.page(page, wrapper);
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("查询成功");
            data.setData(list);
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查找失败" + e.getMessage());
        }
    }

    /**
     * 查询所有歌曲
     */
    @GetMapping("/allSong")
    public Object allSong(@RequestParam(required = false) Long current, @RequestParam(required = false) Long size) {
        try {
            if (current != null && size != null) {
                Page<Song> page = new Page<>();
                page.setCurrent(current);
                page.setSize(size);
                Page<Song> list = songService.page(page);
                if (list.getTotal() != 0) {
                    ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                    data.setMsg("查询成功");
                    data.setData(list);
                    return data;
                }
            } else {
                List<Song> list = songService.list();
                if (list.size() != 0) {
                    ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                    data.setMsg("查询成功");
                    data.setData(list);
                    return data;
                }
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
        return 0;
    }

    /**
     * 强制删除
     *
     * @param fileName
     * @return
     */
    public static boolean forceDelete(String fileName) {
        File f = new File(fileName);
        boolean result = false;
        int tryCount = 0;
        while (!result && tryCount++ < 10) {
            System.out.println("try to delete file " + f.getName() + " cnt:" + tryCount);
            System.gc();
            result = f.delete();
        }
        return result;
    }

}



